<?php
/**
 * Created by PhpStorm.
 * User: bevan
 * Date: 2018/1/6
 * Time: 下午2:16
 */

namespace app\admin\service;

use app\common\model\MenuModel;
use thans\auth\model\AuthGroupModel;
use thans\auth\model\AuthRuleModel;
use think\Db;
use think\Exception;

class MenuService
{
    /**
     *
     * @method 获取菜单列表
     * @version
     * @User: bevan
     * @return
     */
    public function getTreeList($group_id = 0)
    {
        try {

            if ($group_id) {

                if ($group_id == 1) {
                    $auth = AuthRuleModel::field('id')->select();
                    foreach ($auth as $val) {
                        $rule_arr[] = $val['id'];
                    }
                } else {
                    $group    = AuthGroupModel::get($group_id);
                    $rule_arr = explode(',', $group['rules']);
                }

            } else {
                $rule_arr = [];
            }

            $menuModel = new MenuModel();

            $menus = $menuModel->getTreeList($rule_arr);

        } catch (Exception $e) {
            return ['code' => 4001, 'msg' => '获取失败,' . $e->getMessage(), 'data' => []];
        }
        return ['code' => 1001, 'msg' => '获取成功', 'data' => $menus];
    }

    /**
     *
     * @method 获取单个菜单的详情
     * @version
     * @User: bevan
     * @param $id
     * @return
     */
    public function getMenuById($id)
    {
        try {
            $menu = MenuModel::get($id);
        } catch (Exception $e) {
            return ['code' => 4001, 'msg' => '获取失败,' . $e->getMessage(), 'data' => []];
        }

        return ['code' => 1001, 'msg' => '获取成功', 'data' => $menu];
    }

    /**
     *
     * @method 更新菜单信息
     * @version
     * @User: bevan
     * @param $id
     * @param $data
     * @return
     */
    public function update($id, $data)
    {
        $menu = new MenuModel();
        //找到对应的规格id
        $rule_id = $menu->getRuleIdByMenuId($id);
        Db::startTrans();
        try {
            $data['update_time'] = time();
            $menu->allowField(true)->save($data, ['id', $id]);

            //更新规格
            $rule = AuthRuleModel::get($rule_id);

            if ($rule) {
                //更新
                $rule->name      = $data['param'] ? $data['app'] . '/' . $data['controller'] . '/' . $data['action'] . '?' . $data['param'] : $data['app'] . '/' . $data['controller'] . '/' . $data['action'];
                $rule->type      = 'admin_url';
                $rule->app       = $data['app'];
                $rule->status    = 1;
                $rule->title     = $data['name'];
                $rule->condition = isset($data['condition']) ? $data['condition'] : '';

                $rule->save();
            } else {
                //添加
                $new_rule = AuthRuleModel::create([
                    'name'      => $data['param'] ? $data['app'] . '/' . $data['controller'] . '/' . $data['action'] . '?' . $data['param'] : $data['app'] . '/' . $data['controller'] . '/' . $data['action'],
                    'type'      => 'admin_url',
                    'status'    => 1,
                    'app'       => $data['app'],
                    'title'     => $data['name'],
                    'condition' => isset($data['condition']) ? $data['condition'] : '',
                ]);

                $new_rule_id = $new_rule->id;
                //更新
                $menu->rule_id = $new_rule_id;

                $menu->save();
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 4001, 'msg' => '更新失败,' . $e->getMessage(), 'data' => []];
        }

        return ['code' => 1001, 'msg' => '更新成功', 'data' => []];
    }

    /**
     *
     * @method
     * @version
     * @User: bevan
     * @param $id
     * @return
     */
    public function delete($id)
    {
        //判断该菜单下是否有子菜单

        $countMenuChilid = MenuModel::where('parent_id', $id)->count();

        if ($countMenuChilid) {
            //有子菜单
            return ['code' => 4001, 'msg' => '有子菜单,不允许删除', 'data' => []];
        }
        Db::startTrans();
        //删除
        try {
            $rule_id = MenuModel::where('id', $id)->value('rule_id');

            MenuModel::destroy($id);

            AuthRuleModel::destroy($rule_id);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 4001, 'msg' => '删除失败,' . $e->getMessage(), 'data' => []];
        }
        return ['code' => 1001, 'msg' => '删除成功', 'data' => []];
    }

    /**
     *
     * @method 创建新的菜单
     * @version
     * @User: bevan
     * @param $data
     * @return
     */
    public function save($data)
    {
        Db::startTrans();
        try {
            $data['create_time'] = time();
            $data['update_time'] = time();
            $menu                = MenuModel::create($data, true);

            $menu_id = $menu->id;

            //创建对应的规格
            $data['id']     = $menu_id;
            $data['title']  = $data['name'];
            $data['name']   = $data['param'] ? $data['app'] . '/' . $data['controller'] . '/' . $data['action'] . '?' . $data['param'] : $data['app'] . '/' . $data['controller'] . '/' . $data['action'];
            $data['type']   = 'admin_url';
            $data['status'] = 1; // 规则的状态 默认为1启用

            $rule = AuthRuleModel::create($data, true);

            $menu->rule_id = $rule->id;

            $menu->save();

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 4001, 'msg' => '创建失败,' . $e->getMessage(), 'data' => []];
        }

        return ['code' => 1001, 'msg' => '创建成功', 'data' => []];
    }

    /**
     *
     * @method 获取所有的一级菜单列表
     * @version
     * @User: bevan
     * @return
     */
    public function getTopList($data = [], $group_id = 0)
    {
        $menus_sql = MenuModel::where('parent_id', 0)->where('status', 1);

        if ($group_id && $group_id != 1) {
            $group     = AuthGroupModel::get($group_id);
            $rule_arr  = explode(',', $group['rules']);
            $menus_sql = $menus_sql->whereIn('id', $rule_arr);
        }

        if (isset($data['title']) && $data['title']) {
            $menus_sql = $menus_sql->where('name', 'like', '%' . $data['title'] . '%');
        }
        $menus = $menus_sql
            ->order('list_order', 'asc')
            ->select();

        $total_arr = $menus_sql->select();
        $total     = count($total_arr);

        if ($menus === false) {
            return ['code' => 4001, 'msg' => '获取失败', 'data' => []];
        } else {
            return ['code' => 1001, 'msg' => '获取成功', 'data' => $menus, 'total' => $total];
        }
    }

    /**
     * 获取子菜单
     * @param id 菜单父ID
     */
    public function getChildMenu($id, $group_id = 0)
    {
        $rule_arr = [];
        if ($group_id && $group_id != 1) {
            $group    = AuthGroupModel::get($group_id);
            $rule_arr = explode(',', $group['rules']);
        }
        $menuModel = new MenuModel();
        $menu      = $menuModel->getChildList($id, $rule_arr);
        return ['code' => 1001, 'msg' => '获取成功', 'data' => $menu];
    }

    public function getSortList($data)
    {
        $menuModel = new MenuModel();

        $menus = $menuModel->getSortList($data);

        $total = count($menus);

        if ($menus === false) {
            return ['code' => 4001, 'msg' => '获取失败', 'data' => []];
        } else {
            return ['code' => 1001, 'msg' => '获取成功', 'data' => $menus, 'total' => $total];
        }
    }

    /**
     * @title 获取快捷菜单
     */
    public function getShortcutMenu()
    {
        $menus              = [];
        $menu['endpath']    = '/admin/dashboard.html';
        $menu['name']       = '快捷操作';
        $menu['status']     = 1;
        $menu['type']       = 1;
        $menu['checked']    = 1;
        $menu['icon']       = 'layui-icon layui-icon-note';
        $menu['children'][] = [
            'endpath' => '/admin/dashboard.html',
            'name'    => '首页',
            'status'  => '1',
            'type'    => '3',
            'checked' => '1',
        ];
        $menus[] = $menu;
        return ['code' => 1001, 'msg' => '获取成功', 'data' => $menus];
    }

    public function toggle($id)
    {
        $menuModel = new MenuModel();
        if ($menuModel->toggle($id)) {
            return ['code' => 1001, 'msg' => '切换状态成功', 'data' => ''];
        } else {
            return ['code' => 4002, 'msg' => '切换失败', 'data' => ''];
        }
    }
}
